const {app, BrowserWindow} = require('electron')

let mainWindow

// 自定义schema协议
const protocol = 'bilibili'
const scheme= `${protocol}://`
app.setAsDefaultProtocolClient(protocol)
// 协议唤起时携带的参数
let urlParams = {}
// window端处理协议参数
handleSchemeWeakup(process.argv)

// 获取实例运行锁-第一个实例返回true，其他返回false
const goTheLock = app.requestSingleInstanceLock()
if(!goTheLock) {
    app.quit()
}else {
    // 其他实例唤起的处理效果
    app.on('second-instance', (event,argv)=>{
        mainWindow.restore()
        mainWindow.show()
        handleSchemeWeakup(argv)
    })
}

// mac端监听open-url,处理schema协议参数
app.on('open-url', (event,url) => handleSchemeWeakup(url))

app.whenReady().then(()=>{
    createWindow()
})

function createWindow() {
    const width = parseInt(urlParams.width) || 800
    const height = parseInt(urlParams.height) || 600
    if (mainWindow) {
        mainWindow.setSize(width, height)
    } else {
        mainWindow = new BrowserWindow({ width, height })
        mainWindow.loadURL('https://www.bilibili.com/')
    }
}
function handleSchemeWeakup(argv) {
    const url = [].concat(argv).find(v=>v.startsWith(scheme))
    if(!url) return
    const searchParams = new URLSearchParams(url.slice(scheme.length))
    console.log(searchParams.entries(),'en')
    urlParams = Object.fromEntries(searchParams.entries())
    if(app.isReady()) {
        createWindow()
    }
}

